<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/23 0023
 * Time: 10:55
 */
namespace Admin\Model;
use Think\Model\RelationModel;

class ArticleModel extends RelationModel {
    //文章属于分类
    protected $_link = array(
        'category'=> self::BELONGS_TO,
    );

    /***
     * 查出所有分类
     * @return mixed
     */
    function all_categories()
    {
        $Category = M('Category');
        $categories = $Category->where("parent_id = 0")->order('sort_order')->select();
        foreach ($categories as &$category) {
            $children = $Category->where("parent_id = $category[id]")->order('sort_order')->select();
            $category['children'] = $children;
        }

        return $categories;
    }
    /***
     * 查出所有文章
     * @return mixed
     */
    function all_articles()
    {
        $Article = M('Article');
        $Category = M('Category');
        $articles = $Article->order('sort_order desc')->select();
        foreach ($articles as $key => $value) {
            $articles[$key]['category'] = $Category->where("id = $value[category_id]")->find();
        }

        return $articles;
    }
    //自动处理时间
    protected $_auto = array(
        array('time', 'set_time', 3, 'callback'), // 对update_time字段在更新的时候写入当前时间戳
    );

    //把字符串转换成UNix时间戳
    function set_time($time)
    {
        return strtotime($time);
    }

}